package db_servicer

import "fmt"

/*
var ses *ora.Ses
var logger *log.Logger

*/

func User_Register(account, pass, uname string, p_country_id, p_addr_id int32, p_street_info string) Ua_retMsg {

	// logger = log.New(os.Stdout, ">>>>>DB.User_Register:", log.LstdFlags|log.Lshortfile)

	var v_user_id int32
	var v_msg, v_data string
	var v_flag int8 = 0

	if _, err := ses.PrepAndExe("CALL pkg_user_auth.user_register(:p1,:p2,:p3,:p4,:p5,:p6, :p7, :p8, :p9)",
		account, pass, uname, p_country_id, p_addr_id, p_street_info, &v_user_id, &v_msg, &v_data); err != nil {

		logger.Panicf("***Panic in User_Register, retMsg:%v, err: %v ***\n", v_msg, err)
	}

	logger.Println("user_id:", v_user_id, "Msg:", v_msg)

	if v_user_id <= 0 {
		v_flag = int8(v_user_id)
	}
	return Ua_retMsg{Flag: v_flag,
		Message: v_msg,
		User_id: int(v_user_id),
		Data:    v_data}

}

func User_Auth(session_id, uname, pass, ip string, port int32) Ua_retMsg {
	// return  value
	//   if  Flag = 0 : succeed
	//     account_id: user_id  from column user_info.user_id in DB
	//       Message : json format of last three login logs within latest 90 days
	//
	//    if Flag  = -1: failed
	//       account_id and Message: useless

	// logger = log.New(os.Stdout, ">>>>>DB.User_Auth:", log.LstdFlags|log.Lshortfile)

	//	logger.Println("Parameters values:  session_id:", session_id, ",uname:", uname, ",pass:", pass)

	var flag int8 = -1
	var user_id int32
	var msg, data string

	if session_id == "" {
		session_id = "NULL"
	}

	if _, err := ses.PrepAndExe("CALL pkg_user_auth.user_login(:p1,:p2,:p3,:p4,:p5, :p6, :p7 , :p8 )",
		session_id, uname, pass, ip, port, &user_id, &msg, &data); err != nil {

		//		logger.Printf(" Type of port: %T, value of port: %v", port, port)
		logger.Panicf("***Panic in User_Auth, retMsg:%v, err: %v ***\n", msg, err)
	}

	if user_id > 0 {
		flag = 0
	}

	return Ua_retMsg{Flag: flag,
		Message: msg,
		User_id: int(user_id),
		Data:    data,
	}
}

func Chang_password(p_user_id int, p_session_id, p_old_pass, p_new_pass string) Ua_retMsg {
	// return  value
	//   if  Flag = 0 : succeed
	//
	//    if Flag  = -1: failed
	//       account_id and Message: useless

	// logger = log.New(os.Stdout, ">>>>>>DB.Change Password:", log.LstdFlags|log.Lshortfile)

	//	logger.Println("Parameters values:  session_id:", session_id, ",uname:", uname, ",pass:", pass)
	var flag int8
	var msg, data string

	if p_session_id == "" {
		p_session_id = "NULL"
	}

	if _, err := ses.PrepAndExe("CALL pkg_user_auth.Chg_password(:p1,:p2,:p3,:p4,:p5, :p6, :p7 )",
		&flag, &msg, &data, int32(p_user_id), p_session_id, p_old_pass, p_new_pass); err != nil {

		logPanic(fmt.Sprintf("***Panic in Chang_password, msg:%v, err: %v ***\n", msg, err))
	}

	return Ua_retMsg{Flag: flag,
		Message: msg,
		User_id: p_user_id,
		Data:    data,
	}

}
